#!/usr/bin/env python

__doc__ = """
removeFirstTag
==============

:Authors: Karl Norby
:Version: 1.0
:Date: Sept. 5th, 2007

Deletes the first tag found that matches a given tag name in an xml file.

Arguments
---------

1. tagname
2. *optional* filename (from stdin)
3. *optional* output (goes to stdout by default)

"""

import lxml.etree as ET
import os, sys

def removeFirstTag(tagname, xmlInput, output):
    finder = ET.XPath("//" + tagname)

    tree   = ET.parse(xmlInput)
    root   = tree.getroot()
    res    = finder(root)
    if len(res):
        res = res[0]
        if root==res:
            return
        res.getparent().remove(res)
    retval = ET.tostring(tree)
    if output==None:
        return retval
    print >> output, retval

    
def main():
    argc = len(sys.argv)
    if argc<2 or argc>4:
        raise "error: Wrong number of arguments"
    expr = sys.argv[1]

    if argc==3 or argc==4:
        filename = sys.argv[2]
        if not os.path.isfile(filename):
            raise IOError, "%s is not a file" % filename
    else:
        filename = sys.stdin
    
    if argc==4:
        output = sys.argv[3]
        output = open(output, "w")
    else:
        output = sys.stdout

    removeFirstTag(expr, filename, output)
    sys.exit(0)

if __name__=="__main__":
    main()
